<template>
  <div class="app-container">
    <div class="app-layout">
      <!-- 左侧类别列表 -->
      <div class="left-panel">
        <div class="pane">
          <div class="head">
            <span>参数类别</span>
            <div style="flex: 1;"></div>
            <el-button type="primary" @click="handleAddCategory" size="small" style="margin-right: 12px;">
              <el-icon><Plus /></el-icon>新增类别
            </el-button>
          </div>
          <div class="body">
            <el-table
              :data="categoryList" 
              style="width: 100%" 
              v-loading="categoryLoading"
              @row-click="handleCategoryClick"
              :highlight-current-row="true"
              @row-contextmenu="(row: ParamModelCategoryVO, _column: any, event: MouseEvent) => handleContextMenu(event, row)"
              row-key="id"
              :tree-props="{
                children: 'children',
                hasChildren: 'hasChildren'
              }"
              default-expand-all
			  :show-header="false"
            >
              <el-table-column prop="name" label="类别名称" />
            </el-table>
          </div>
        </div>
      </div>

      <!-- 右侧参数列表 -->
      <div class="right-panel">
        <div class="pane">
          <div class="head">
            <span>参数列表 {{ getCurrentCategoryName() }}</span>
            <div style="flex: 1;"></div>
            <el-button type="primary" @click="handleAddModel" size="small" style="margin-right: 12px;">
              <el-icon><Plus /></el-icon>新增参数
            </el-button>
          </div>
          <div class="body">
            <el-form :inline="true" class="search-bar">
              <el-form-item label="关键字">
                <el-input v-model="queryParams.keywords" placeholder="参数名称" clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery">
                  <el-icon><Search /></el-icon>搜索
                </el-button>
                <el-button @click="resetQuery">
                  <el-icon><Refresh /></el-icon>重置
                </el-button>
              </el-form-item>
            </el-form>

            <el-table 
              :data="modelList" 
              style="width: 100%" 
              v-loading="modelLoading"
              height="calc(100vh - 320px)"
            >
              <el-table-column prop="name" label="参数名称" />
              <el-table-column prop="type" label="参数类型" />
              <el-table-column prop="sort" label="排序" width="80" />
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="scope">
                  <el-button 
                    link 
                    type="primary" 
                    @click="handleEditModel(scope.row)"
                  >编辑</el-button>
                  <el-button 
                    link 
                    type="danger" 
                    @click="handleDeleteModel(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-pagination
              v-if="total > 0"
              :total="total"
              v-model:current-page="queryParams.cur"
              v-model:page-size="queryParams.limit"
              class="pagination"
              @current-change="getModelList"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 右键菜单 -->
    <div 
      v-show="contextMenuVisible" 
      class="context-menu"
      :style="{
        left: contextMenuPosition.x + 'px',
        top: contextMenuPosition.y + 'px'
      }"
    >
      <ul>
        <li @click="handleEditCategory(currentRow)">
          <el-icon><Edit /></el-icon>
          编辑
        </li>
        <li @click="handleDeleteCategory(currentRow)">
          <el-icon><Delete /></el-icon>
          删除
        </li>
      </ul>
    </div>

    <!-- 点击空白处关闭右键菜单 -->
    <div 
      v-show="contextMenuVisible" 
      class="context-menu-mask" 
      @click="closeContextMenu"
      @contextmenu.prevent
    />

    <!-- 类别表单弹窗 -->
    <param-category-form-dialog
      v-model="categoryDialog.visible"
      :title="categoryDialog.title"
      :category="categoryDialog.data"
      :category-tree-data="categoryList"
      @success="getCategoryList"
    />

    <!-- 参数表单抽屉 -->
    <model-form-drawer
      v-model="modelDialog.visible"
      :title="modelDialog.title"
      :model="modelDialog.data"
      :categories="flattenCategories"
      @success="getModelList"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import type { ParamModelCategoryVO, ParamModelVO } from '@/api/biz/parammodel';
import ParamModelAPI from '@/api/biz/parammodel';
import ParamCategoryFormDialog from './components/ParamCategoryFormDialog.vue';
import ModelFormDrawer from './components/ModelFormDrawer.vue';

// 查询参数
const queryParams = reactive({
  keywords: '',
  categoryId: '',
  cur: 1,
  limit: 10
});

// 数据列表
const categoryList = ref<ParamModelCategoryVO[]>([]);
const modelList = ref<any>([]);
const total = ref(0);

// 加载状态
const categoryLoading = ref(false);
const modelLoading = ref(false);

// 右键菜单
const contextMenuVisible = ref(false);
const contextMenuPosition = reactive({ x: 0, y: 0 });
const currentRow = ref<ParamModelCategoryVO | null>(null);

// 弹窗数据
const categoryDialog = reactive({
  visible: false,
  title: '',
  data: {} as ParamModelCategoryVO
});

const modelDialog = reactive({
  visible: false,
  title: '',
  data: {} as ParamModelVO
});

// 获取类别列表
const getCategoryList = async () => {
  categoryLoading.value = true;
  try {
    const data = await ParamModelAPI.getCategoryPage({});
    categoryList.value = convertToTree(data);
  } finally {
    categoryLoading.value = false;
  }
};

// 数组转树形结构
const convertToTree = (list: ParamModelCategoryVO[]) => {
  if (!list) return [];
  const map = new Map();
  const result: ParamModelCategoryVO[] = [];

  // 先用Map存储每个节点
  list.forEach(item => {
    map.set(item.id, { 
      ...item, 
      children: undefined // 初始化时不设置children数组
    });
  });

  // 构建树形结构
  list.forEach(item => {
    const node = map.get(item.id);
    if (item.parentId && map.has(item.parentId)) {
      const parent = map.get(item.parentId);
      if (!parent.children) {
        parent.children = [];
      }
      parent.children.push(node);
    } else {
      result.push(node);
    }
  });

  return result;
};

// 获取参数列表
const getModelList = async () => {
  modelLoading.value = true;
  try {
    const data = await ParamModelAPI.getModelPage(queryParams);
	if (data) {
	  modelList.value = data.list;
	  total.value = data.totalRow;
	}
  } finally {
    modelLoading.value = false;
  }
};

// 搜索
const handleQuery = () => {
  queryParams.cur = 1;
  getModelList();
};

// 重置
const resetQuery = () => {
  queryParams.keywords = '';
  queryParams.categoryId = '';
  if (categoryList.value?.[0]) {
    handleCategoryClick(categoryList.value[0]);
  } else {
    handleQuery();
  }
};

// 处理类别点击
const handleCategoryClick = (row: ParamModelCategoryVO) => {
  queryParams.categoryId = row.id;
  queryParams.cur = 1;
  getModelList();
};

// 获取当前类别名称
const getCurrentCategoryName = () => {
  if (!queryParams.categoryId) return '';
  const findCategory = (list: ParamModelCategoryVO[]): ParamModelCategoryVO | undefined => {
    for (const item of list) {
      if (item.id === queryParams.categoryId) return item;
      if (item.children?.length) {
        const found = findCategory(item.children);
        if (found) return found;
      }
    }
    return undefined;
  };
  const category = findCategory(categoryList.value || []);
  return category ? `- ${category.name}` : '';
};

// 右键菜单
const handleContextMenu = (e: MouseEvent, row: ParamModelCategoryVO) => {
  e.preventDefault();
  contextMenuVisible.value = true;
  contextMenuPosition.x = e.clientX;
  contextMenuPosition.y = e.clientY;
  currentRow.value = row;
};

const closeContextMenu = () => {
  contextMenuVisible.value = false;
  currentRow.value = null;
};

// 新增类别
const handleAddCategory = () => {
  categoryDialog.title = '新增类别';
  categoryDialog.data = {} as ParamModelCategoryVO;
  categoryDialog.visible = true;
};

// 编辑类别
const handleEditCategory = (row: ParamModelCategoryVO | null) => {
  if (!row) return;
  categoryDialog.title = '编辑类别';
  categoryDialog.data = { ...row };
  categoryDialog.visible = true;
  closeContextMenu();
};

// 删除类别
const handleDeleteCategory = (row: ParamModelCategoryVO | null) => {
  if (!row) return;
  ElMessageBox.confirm('确认要删除该类别吗？', '警告', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(async () => {
      try {
        await ParamModelAPI.deleteCategoryByIds(row.id);
        ElMessage.success('删除成功');
        await getCategoryList();
      } catch (error) {
        ElMessage.error('删除失败：' + (error as Error).message);
      } finally {
        closeContextMenu();
      }
    })
    .catch(() => {
      closeContextMenu();
    });
};

// 新增参数
const handleAddModel = () => {
  if (!queryParams.categoryId) {
    ElMessage.warning('请先选择类别');
    return;
  }
  modelDialog.title = '新增参数';
  modelDialog.data = {
    categoryId: queryParams.categoryId
  } as ParamModelVO;
  modelDialog.visible = true;
};

// 编辑参数
const handleEditModel = (row: ParamModelVO) => {
  modelDialog.title = '编辑参数';
  modelDialog.data = { ...row };
  modelDialog.visible = true;
};

// 删除参数
const handleDeleteModel = (row: ParamModelVO) => {
  ElMessageBox.confirm('确认要删除该参数吗？', '警告', {
    type: 'warning'
  }).then(async () => {
    await ParamModelAPI.deleteModelByIds(row.id);
    ElMessage.success('删除成功');
    getModelList();
  });
};

// 展平类别树，用于参数表单中的类别选择
const flattenCategories = computed(() => {
  if (!categoryList.value) return [];
  const result: ParamModelCategoryVO[] = [];
  const flatten = (list: ParamModelCategoryVO[]) => {
    if (!list) return;
    list.forEach(item => {
      result.push(item);
      if (item.children?.length) {
        flatten(item.children);
      }
    });
  };
  flatten(categoryList.value);
  return result;
});

onMounted(() => {
  getCategoryList();
});
</script>

<style lang="scss" scoped>
.context-menu {
  position: fixed;
  z-index: 9999;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
    
    li {
      padding: 8px 16px;
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      color: var(--el-text-color-regular);
      
      &:hover {
        background-color: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
      }
      
      .el-icon {
        font-size: 16px;
      }
    }
  }
}

.context-menu-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9998;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}

.left-panel{
	width: 300px; 
	margin-right: 16px;
}
.right-panel{
	width: calc(100% - 316px);
}

:deep(.el-table th.el-table__cell) {
	/* background-color: #fafafa; */
	background-color: #eee;
	background-image: url();
	background-image: -webkit-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
	background-image: -moz-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
	background-image: -o-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
	background-image: linear-gradient(to bottom, #f2f2f2 0, #fafafa 100%);
	font-size: 12px;
}
</style> 